#include <stdio.h>
#include "esp_err.h"
#include "ble_app.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "nvs_flash.h"
#include "app.h"

extern tSys_Flag Sys_Flag;
extern tSys_Status Sys_Status;
SemaphoreHandle_t sem_Ble_Get_Data;



void Ble_Send_Successive_Data(void )
{
    cJSON *ReData = NULL;
    char *str = NULL;
    ReData = cJSON_CreateObject();  // 初始化返回数据结构

    cJSON_AddNumberToObject(ReData, "CurrentLev", Sys_Status.Current_Value);

    str = cJSON_PrintUnformatted(ReData);
    Sys_Flag.Ble_Send_Data_Flag = 1;
    
    memcpy( Sys_Status.Ble_SendData_Buff , str , strlen(str )+ 1 );
    ESP_LOGI("Ble", " Ble_SendData_Buff = %s\n",  Sys_Status.Ble_SendData_Buff);
    cJSON_free(str);
    cJSON_Delete(ReData);

}
void Ble_Task(void* param)
{
    int32_t Old_Value = 0;
    uint32_t current_time =0 , old_time = 0;
    int time_cont = 0;
    ESP_ERROR_CHECK(nvs_flash_init());
    ble_cfg_net_init();

    Ble_Print_Sno();
    

    sem_Ble_Get_Data = xSemaphoreCreateBinary();   // 创建显示更新信号量

    while(1)
    {
        vTaskDelay(1);
        if( Sys_Flag.Ble_Send_Data_Flag == 1 )
        {
            Sys_Flag.Ble_Send_Data_Flag = 0;
            ble_set_ch2_value(Sys_Status.Ble_SendData_Buff , strlen(Sys_Status.Ble_SendData_Buff ));
        }
        if( Sys_Flag.Ble_SetDataRate_Flag == 1 && Sys_Flag.Led_Start_Flag == 1)
        {
            if( Old_Value != Sys_Status.Current_Value)
            {
                Old_Value = Sys_Status.Current_Value;
                time_cont = 0;
                vTaskDelay(Sys_Status.Ble_Send_Rate);
                Ble_Send_Successive_Data();
            }
            else    // 没有变化的时候，每秒主动触发一次发送
            {
                current_time = esp_timer_get_time() / 1000; // 获取当前时间（豪秒）
                if( (current_time - old_time) > 999 )
                {
                    old_time = current_time;
                    Old_Value = -1 ;
                }
            }
        }
    }
}